<template>
    <div style="padding-left:5px;">
<!--        windowInnerWidth:{{windowInnerWidth}}-->
        <el-row>
            <el-col align="left">
                <el-form label-width="100px">
                    <el-form-item label="距离：">
                        <el-input-number v-model="distance" :min="1" :max="1000" :step="100" @change="changeDistance"></el-input-number>米
                    </el-form-item>
                    <el-form-item label="甲速度：">
                        <el-input-number v-model="v1" :min="0" :max="1000" :step="50" @change="goHome"></el-input-number>米/秒
                    </el-form-item>
                    <el-form-item label="乙速度：">
                        <el-input-number v-model="v2" :min="0" :max="1000"  :step="50" @change="goHome"></el-input-number>米/秒
                    </el-form-item>
                    <el-form-item label="狗速度：">
                        <el-input-number v-model="v3" :min="1" :max="1000000" :step="50" @change="goHome"></el-input-number>米/秒
                    </el-form-item>
                    <el-form-item label-width="0" style="padding-left: 10px;">
                        耗时：{{parseInt(timeDiff / 1000)}}秒
                        甲路程：{{getDistanceShown(parseInt(v1 * timeDiff / 1000))}}米
                        乙路程：{{getDistanceShown(parseInt(v2 * timeDiff / 1000))}}米
<!--                        狗路程：{{parseInt(distance3Passed)}}米-->
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-row>
            <el-col align="left">
                <el-button type="primary" @click="goHome">回到起点</el-button>
                <el-button type="primary" @click="start">（重新）开始</el-button>
                <el-button type="primary" @click="pause" v-if="!stopped">{{paused ? '恢复' : '暂停'}}</el-button>
            </el-col>
        </el-row>
        <div style="padding-left:10px;">
            <v-stage ref="stage" :config="stageSize" >
                <v-layer ref="layer">
                    <v-line :config="{
                    x: 0,
                    y: 100,
                    points: [0, 0, distanceShown, 0],
                    tension: 0.5,
                    closed: true,
                    stroke: 'black',
                    fillLinearGradientStartPoint: { x: -50, y: -50 },
                    fillLinearGradientEndPoint: { x: 50, y: 50 },
                    fillLinearGradientColorStops: [0, 'red', 1, 'yellow']
                  }"/>


                    <v-circle ref="circle1" :config="{x: x1, y: 80, radius: 5, fill: 'green'}"/>
                    <v-circle ref="circle2" :config="{x: x2, y: 80, radius: 5, fill: 'red'}"/>
                    <v-circle ref="circle2" :config="{x: x3, y: 120, radius: 5, fill: 'dog'}"/>

                </v-layer>
            </v-stage>
        </div>
<!--        <div v-for="(distanceInfo, index) in distance3SegmentArr" :key="index">-->
<!--            <div>{{distanceInfo}}</div>-->
<!--        </div>-->
        <el-table v-if="distance3SegmentArr && distance3SegmentArr.length > 0" :data="distance3SegmentArr" show-summary :summary-method="getSummaries">
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>
            <el-table-column prop="distancePassed" label="狗经过路程(米)" width="120px">
                <template slot-scope="scope">
                    <span>{{scope.row.distancePassed | rounding}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="desc" label="和谁相遇" width="100px"></el-table-column>
        </el-table>

        <div style="height:300px;margin-top:30px;" v-show="distance3SegmentArr && distance3SegmentArr.length > 0" >
            <v-chart :option="option" :autoresize="true"/>
        </div>
    </div>

</template>

<script>
    // import v-chart from 'vue-echarts'
    import lodash from 'lodash'
    import Konva from "konva";

    export default {
        // components:{ECharts},
        data() {
            return {
                width: window.innerWidth - 50,
                height: 200,
                windowInnerWidth: 0,
                anim: null,
                distance: 900,
                timeDiff: 0,
                x1: 0,
                v1: 80,
                x2: 0,
                v2: 100,
                x3: 0,
                v3: 300,
                direction3: 1,
                distance3Segment: 0,
                distance3SegmentArr: [],
                paused: false,
                stopped: true,
                option: {},
                optionTemplate: {
                    title: {
                        text: '狗路程条形图'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (params) {
                            let html = params[0].name+"<br>";
                            for(let i = 0; i < params.length; i++){
                                // console.log('params[i]:', params[i])
                                html += params[i].marker
                                html += params[i].seriesName + ": " + parseInt(params[i].value)  + "米<br>";
                            }
                            return html;
                        }
                    },
                    legend: {
                        data: ['狗']
                    },
                    xAxis: {
                        type: 'category',
                        data: [],
                        name: '和谁相遇'
                    },
                    yAxis: {
                        type: 'value',
                        name: '相遇所经过路程'
                    },
                    series: [{
                        name: '狗',
                        data: [],
                        type: 'bar'
                    }]
                }
            };
        },
        filters: {
            rounding (value) {
                return value.toFixed(0)
            }
        },
        methods: {
            getDistanceShown(distancePassed) {
              return parseInt(distancePassed * this.distanceShown / this.distance)
            },
            getSummaries() {
                const sums = [];
                let allDistancePassed = 0
                this.distance3SegmentArr.forEach(r => {
                    allDistancePassed += r.distancePassed
                })

                sums.push('合计')
                sums.push(allDistancePassed.toFixed(0))
                sums.push('')
                return sums
            },
            changeDistance() {
                this.goHome()
            },
            start() {
                this.goHome()
                this.stopped = false
                this.anim.start();
            },
            pause() {
              this.paused = !this.paused
            },
            goHome() {
                if(this.anim) {
                    this.anim.stop();
                }
                this.paused = false
                this.stopped = true
                this.timeDiff = 0
                this.direction3 = 1
                this.x1 = 0
                this.x2 = this.distanceShown
                this.x3 = 0
                this.distance3Segment = 0
                this.distance3SegmentArr = []
                this.option = {}
            },
            changeSize(e) {
                // to() is a method of `Konva.Node` instances
                e.target.to({
                    scaleX: Math.random() + 0.8,
                    scaleY: Math.random() + 0.8,
                    duration: 0.2
                });
            },
            renderResize() {
                this.windowInnerWidth = window.innerWidth - 50
                this.goHome()
            },
            stop() {
                if(this.anim) {
                    this.anim.stop()
                }
                this.stopped = true

                let option = lodash.cloneDeep(this.optionTemplate)
                this.distance3SegmentArr.forEach(r => {
                    option.xAxis.data.push(r.desc)
                    option.series[0].data.push(r.distancePassed)
                })
                this.option = option
            },
        },
        computed: {
            stageSize() {
              return {
                width: this.windowInnerWidth,
                height: this.height
              }
            },
            distanceShown() {
                return Math.min(this.distance, this.windowInnerWidth - 50)
            },
            distance3Passed() {
                let result = 0
                this.distance3SegmentArr.forEach(r => {
                    result += r.distancePassed
                })
                return result
            },
        },
        mounted() {
            this.windowInnerWidth = window.innerWidth
            const vm = this;
            window.addEventListener("orientationchange", this.renderResize, false)

            this.x2 = this.distanceShown

            const circle1 = this.$refs.circle1.getNode();
            this.anim = new Konva.Animation(function(frame) {
                if(!vm.paused) {
                    vm.timeDiff+= frame.timeDiff
                    let delta1 = vm.v1 * (frame.timeDiff / 1000);
                    let delta2 = vm.v2 * (frame.timeDiff / 1000);
                    let delta3 = vm.v3 * (frame.timeDiff / 1000) * vm.direction3;
                    // console.log('frame.timeDiff:', frame.timeDiff, 'delta1:', delta1, 'delta2:', delta2)

                    if(vm.x1 < vm.x2) {
                        vm.x1 += delta1
                    }

                    if(vm.x2 > vm.x1) {
                        vm.x2 -= delta2
                    }

                    vm.x3 += delta3
                    vm.distance3Segment += Math.abs(delta3)
                    if(vm.direction3 > 0 && vm.x3 >= vm.x2) {
                        // console.log('here1')

                        vm.direction3 *= -1

                        vm.distance3SegmentArr.push({'desc': '乙', 'distancePassed': vm.distance3Segment})
                        vm.distance3Segment = 0
                    } else if(vm.direction3 < 0 && vm.x3 <= vm.x1) {
                        // console.log('here2')

                        vm.direction3 *= -1

                        vm.distance3SegmentArr.push({'desc': '甲', 'distancePassed': vm.distance3Segment})
                        vm.distance3Segment = 0
                    }

                    if(vm.x1 >= vm.x2) {
                        vm.x1 = vm.x2 - 2
                        vm.stop()
                    }
                }
            }, circle1.getLayer());

        }
    };
</script>
